package demo.thread;

import java.util.Random;

public class MyBlockingQueue {
    private int[] items = new int[10000];
    private volatile int size = 0;
    private volatile int head = 0;
    private volatile int tail = 0;

    /**
     * 实现进队列
     * @param value value
     * @throws InterruptedException e
     */
    public synchronized void put(int value) throws InterruptedException {
        while (size == items.length){
            this.wait();
        }
        items[tail] = value;
        tail = (tail + 1) % items.length;
        size++;
        notifyAll();
    }

    /**
     * 实现出队列
     * @return value
     * @throws InterruptedException e
     */
    public synchronized int take() throws InterruptedException {
        while (size == 0){
            this.wait();
        }
        int tmp = items[head];
        head = (head + 1) % items.length;
        size--;
        notifyAll();
        return tmp;
    }

    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue blockingQueue = new MyBlockingQueue();
        Thread customer = new Thread(() -> {
            while (true){
                try {
                    int value = blockingQueue.take();
                    System.out.println("消费者消费 " + value);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread producer = new Thread(() -> {
            while (true){
                try {
                    int value = new Random().nextInt(100);
                    blockingQueue.put(value);
                    System.out.println("生产者生产 " + value);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        customer.start();
        producer.start();
        customer.join();
        producer.join();
    }
}
